import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

// 布局组件
import AppLayout from '@/views/layout/AppLayout.vue'
import AdminLayout from '@/views/layout/AdminLayout.vue'
import IndexView from '@/views/IndexView.vue'

// 登录注册
import LoginView from '@/views/login/LoginView.vue'
import RegisterView from '@/views/register/RegisterView.vue'

// 团队相关
import TeamBind from '@/views/team/TeamBind.vue'
import TeamInfo from '@/views/team/TeamInfo.vue'

// 检测相关
import DetectCenter from '@/views/detect/detectCeter.vue'
import DetectResult from '@/views/detect/detectResult.vue'
import DetectCharts from '@/views/detect/detectCharts.vue'
import DetectMonitor from '@/views/detect/detectMonitor.vue'

// 管理员相关
import UserManagement from '@/views/admin/UserManagement.vue'
import AdPersonalInfo from '@/views/adperson/AdpersonalInfo.vue'
// 个人中心相关
import PersonalInfo from '@/views/person/PersonalInfo.vue'
import PersonalSettings from '@/views/person/PersonalSettings.vue'

// 导入新组件
import SystemMessage from '@/views/message/SystemMessage.vue'
import TeamMessage from '@/views/message/TeamMessage.vue'
import SendMessage from '@/views/admin/SendMessage.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView
    },
    // 用户系统路由
    {
      path: '/',
      name: 'layout',
      component: AppLayout,
      redirect: '/home',
      meta: { requiresAuth: true },
      children: [
        {
          path: 'home',
          name: 'home',
          component: IndexView,
          meta: { requiresAuth: true }
        },
        {
          path: 'team-bind',
          name: 'team-bind',
          component: TeamBind,
          meta: {
            requiresAuth: true,
            title: '团队成员管理'
          }
        },
        {
          path: 'team-info',
          name: 'team-info',
          component: TeamInfo,
          meta: {
            requiresAuth: true,
            title: '团队基本信息'
          }
        },
        {
          path: 'ceter',
          name: 'detect-center',
          component: DetectCenter,
          meta: { requiresAuth: true }
        },
        {
          path: 'result',
          name: 'detect-result',
          component: DetectResult,
          meta: { requiresAuth: true }
        },
        {
          path: 'charts',
          name: 'detect-charts',
          component: DetectCharts,
          meta: { requiresAuth: true }
        },
        {
          path: 'monitor',
          name: 'detect-monitor',
          component: DetectMonitor,
          meta: { requiresAuth: true }
        },
        {
          path: 'personal',
          name: 'personal-info',
          component: PersonalInfo,
          meta: {
            requiresAuth: true,
            title: '个人信息'
          }
        },
        {
          path: 'settings',
          name: 'personal-settings',
          component: PersonalSettings,
          meta: {
            requiresAuth: true,
            title: '账户设置'
          }
        },
        {
          path: 'message',
          name: 'message',
          meta: { requiresAuth: true },
          children: [
            {
              path: 'system',
              name: 'system-message',
              component: SystemMessage,
              meta: { requiresAuth: true }
            },
            {
              path: 'team',
              name: 'team-message',
              component: TeamMessage,
              meta: { requiresAuth: true }
            }
          ]
        }
      ]
    },
    // 管理员系统路由
    {
      path: '/admin',
      name: 'admin-layout',
      component: AdminLayout,
      redirect: '/admin/users',
      meta: { requiresAuth: true, requiresAdmin: true },
      children: [
        {
          path: 'users',
          name: 'admin-users',
          component: UserManagement,
          meta: { requiresAuth: true, requiresAdmin: true }
        },
        {
          path: 'message',
          name: 'admin-send-message',
          component: SendMessage,
          meta: { requiresAuth: true, requiresAdmin: true }
        },
        {
          path: 'person',
          name: 'admin-personal-info',
          component: AdPersonalInfo,
          meta: {
            requiresAuth: true,
            requiresAdmin: true,
            title: '管理员信息'
          }
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/login'
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 获取token和角色信息
  const adminToken = localStorage.getItem('admin-token')
  const userToken = localStorage.getItem('user-token')
  const isAdmin = localStorage.getItem('admin-role') === 'admin'
  const token = adminToken || userToken
  const isAuthenticated = !!token

  // 如果访问的是登录或注册页面
  if (to.name === 'login' || to.name === 'register') {
    if (isAuthenticated) {
      // 已登录用户访问登录页，根据角色重定向
      if (isAdmin) {
        next({ name: 'admin-users' })
      } else {
        next({ name: 'home' })
      }
    } else {
      // 未登录用户可以访问登录页
      next()
    }
    return
  }

  // 对于需要认证的页面
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      // 未登录用户重定向到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      // 检查管理员权限
      if (to.matched.some((record) => record.meta.requiresAdmin)) {
        if (!isAdmin) {
          ElMessage.error('需要管理员权限')
          next({ name: 'home' })
          return
        }
      }
      next()
    }
  } else {
    // 不需要认证的页面直接放行
    next()
  }
})

export default router
